﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using UwaySoft.EsheetServer.Help.SmcService;
using UwaySoft.EsheetServer.Help.Template;
using UwaySoft.EsheetServer.BizLogic;
using UwaySoft.EsheetServer.DataLayer;
using UwaySoft.EsheetServer.Help.Attributes;

namespace UwaySoft.EsheetServer.Help
{
    public abstract class SmcServiceHelper
    {
        /// <summary>
        /// 短信目标用户
        /// </summary>
        public struct MessageTagUser
        {
            public string Caption { get; set; }
            public string UserName { get; set; }
            public string UserPhone { get; set; }            
            public string Conetent { get; set; }            
        }

        private readonly SmcServiceClient client;

        protected SmcServiceHelper()
        {
            client = new SmcServiceClient();
        }

        protected virtual int SendShortMessage(string userPhone, string content)
        {
            return client.deliver(
                "1", "c4ca4238a0b923820dcc509a6f75849b", 2, 1, 1, userPhone, 1, content, string.Empty);
        }
    }

    public class SmcServiceHelper<T> : SmcServiceHelper where T : BaseTemplate
    {
        public SmcServiceHelper(T template) : base()
        {
            Template = template;
        }

        public T Template { get; private set; }

        private ISqlHelper SqlHelper 
        { 
            get { return Application.SqlHelper; } 
        }

        public void SendShortMessage()
        {
            try
            {
                IEnumerable<MessageTagUser> users = GetMessageTagUsers();

                if (users == null || users.Count() == 0)
                {
                    return;
                }

                foreach (var usr in users)
                {
                    try
                    {
                        int result = SendShortMessage(usr.UserPhone, usr.Conetent);

                        if (result == 0)
                        {
                            Log.Info(string.Format("已发送短信：{0} {1} \r\n{2}", usr.UserName, usr.UserPhone, usr.Conetent));
                        }
                        else
                        {
                            Log.Info(string.Format("短信发送失败：{0} {1} \r\n{2}", usr.UserName, usr.UserPhone, usr.Conetent));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        private IEnumerable<MessageTagUser> GetMessageTagUsers()
        {
            if (Template is NewSheetModel)
            {
                return GetMessageTagUsersByNewSheetModel((NewSheetModel)(object)Template);
            }
            return null;
        }

        private IEnumerable<MessageTagUser> GetMessageTagUsersByNewSheetModel(NewSheetModel newSheetModel)
        {
            var cityid = new UserCityHelper().GetCityId(newSheetModel.Usercomplaintcity);
            var lstUser = new List<MessageTagUser>();
            var commandText = string.Format(
               @"SELECT DISTINCT A.USER_NAME, A.USER_PHONE
                  FROM CFG_ESHEETSVRSMC A, CFG_ESHEETSVRSMC_TIMEPERIOD B
                 WHERE A.ID = B.ESHEETSVRSMC_ID
                   AND ENABLE = 1
                   AND TYPE = 1
                   AND bitand(A.DAYOFWEEK, {2}) = {2}
                   AND (B.STARTHOUR <= {0} AND B.ENDHOUR >= {0} AND B.STARTMINUTE <= {1} AND
                       B.ENDMINUTE >= {1})
                   AND CITY_ID = {3}", 
                DateTime.Now.Hour,
                DateTime.Now.Minute,
                (int)Math.Pow(2d, (int)DateTime.Now.DayOfWeek),
                cityid != -1 ? cityid : new UserCityHelper().GetCityId(newSheetModel.Usercity));

            using (var reader = SqlHelper.ExecuteReader(commandText))
            {
                Type type = newSheetModel.GetType();

                while (reader.Read())
                {
                    lstUser.Add(new MessageTagUser 
                    {
                        UserName = reader.GetString("USER_NAME"),
                        UserPhone = string.Format("<PHONE>{0}</PHONE>", reader.GetString("USER_PHONE")),
                        Caption = "新派发工单",
                        Conetent = GetContentByType(
                            type, ConfigurationManager.AppSettings["SmcMsgTemplate"].Replace("[username]", reader.GetString("USER_NAME")), newSheetModel)
                    });
                }
            }

            return lstUser;
        }

        private string GetContentByType(Type type, string contents, object instance)
        {
            if (type == null || contents == null || contents == string.Empty)
            {
                return string.Empty;
            }

            PropertyInfo[] properties = type.GetProperties();

            foreach (var property in properties)
            {
                if (property == null)
                {
                    continue;
                }

                contents = contents.Replace("[" + property.Name.ToLower() + "]", property.GetValue(instance, null).ToString());
            }

            return contents;            
        }
    }
}
